package mvv.learn.spring.utitilies;

import java.io.IOException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * @author Manh Vu
 */
public class JsonUtils {
	private static final Logger log = LoggerFactory.getLogger(JsonUtils.class);

	private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper();

	public static String objectToJson(Object o) {
		try {
			return OBJECT_MAPPER.writeValueAsString(o);
		}catch (JsonProcessingException e) {
			log.error(e.getMessage(), e);
		}

		return "";
	}

	public static <T> T jsonToObject(String json, Class<T> clazz) {
		try {
			return OBJECT_MAPPER.readValue(json, clazz);
		}catch (IOException e) {
			log.error(e.getMessage(), e);
		}

		return null;
	}

	public static String getPrettyPrintJson(Object o) {
		try {
			return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(o);
		}catch (JsonProcessingException e) {
			log.error(e.getMessage(), e);
		}

		return "";
	}

	public static ObjectMapper getObjectMapper() {
		return OBJECT_MAPPER;
	}
}
